package im.composer.media.sound.storage;

import java.io.IOException;

import javax.sound.sampled.AudioFormat;

import im.composer.media.sound.codec.FloatOutputStream;

import org.jaudiolibs.audioservers.AudioConfiguration;
import org.tritonus.share.sampled.FloatInputStream;

public abstract class AudioDataSource implements AutoCloseable,Comparable<AudioDataSource>{

	private transient FloatInputStream fis;
	private transient FloatOutputStream fos;
	private String path;

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public synchronized final FloatInputStream getInputStream() throws IOException {
		if (fis == null) {
			fis = openInputStream(path);
		}
		return fis;
	}

	public synchronized final FloatOutputStream getOutputStream(AudioConfiguration ctx) throws IOException {
		if (fos == null) {
			fos = openOutputStream(path,ctx);
		}
		return fos;
	}

	protected abstract FloatInputStream openInputStream(String path) throws IOException;

	protected abstract FloatOutputStream openOutputStream(String path, AudioConfiguration ctx) throws IOException;

	@Override
	public synchronized void close() throws Exception {
		if(fis!=null){
			try {
				fis.close();
			} catch (Exception e) {
			}
			fis = null;
		}
		if(fos!=null){
			try {
				fos.close();
			} catch (Exception e) {
			}
			fos = null;
		}
	}

	@Override
	public int compareTo(AudioDataSource o) {
		return path.compareTo(o.path);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((path == null) ? 0 : path.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		AudioDataSource other = (AudioDataSource) obj;
		if (path == null) {
			if (other.path != null)
				return false;
		} else if (!path.equals(other.path))
			return false;
		return true;
	}
}
